#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <unistd.h>

class Sock
{
public:
    static int Socket()
    {
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "socket error..." << std::endl;
            exit(2);
        }

        return sockfd;
    }

    static void Bind(int listen_sockfd, uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if(bind(listen_sockfd, (struct sockaddr*)&local, sizeof(local)) == -1){
            std::cerr << "bind error..." << std::endl;
            exit(3);
        }

        std::cout << "bind success..." << std::endl;
    }

    static void Listen(int listen_sockfd)
    {
        static const int backlog = 5;
        if(listen(listen_sockfd, backlog) < 0){
            std::cerr << "listen error..." << std::endl;
            exit(4);
        }

        std::cout << "listen success..." << std::endl;
    }

    static void Connect(int sockfd, std::string ip, uint16_t port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        peer.sin_addr.s_addr = inet_addr(ip.c_str());
        if(connect(sockfd, (struct sockaddr*)&peer, sizeof(peer)) < 0){
            std::cerr << "connect error..."  << std::endl;
            exit(5);
        }
    }

    static int Accept(int listen_sockfd)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int sockfd = accept(listen_sockfd, (struct sockaddr*)&peer, &len);
        if(sockfd < 0){
            std::cerr << "accept error" << std::endl;
            exit(1);
        }

        uint16_t port = ntohs(peer.sin_port);
        std::cout << "get a new link->" << port << std::endl;
        return sockfd;
    }
};
